package admin

import (
	"github.com/gin-gonic/gin"
	"github.com/shopspring/decimal"
	"gorm.io/gorm"
	"mojieshi/define"
	"mojieshi/models"
	"net/http"
	"strconv"
	"strings"
	"time"
)

// 获取商品列表
type FuWuData struct {
	ShopProduct PostList            `json:"shop_product"`
	TjProduct   []models.MFuProduct `json:"tj_product"`
	FuGuiGe     []MShopGuigeFuJson  `json:"fu_gui_ge"`
}
type MShopGuigeFuJson struct {
	ID          int                 `gorm:"type:int(11); primaryKey" json:"id"`
	Aid         int                 `gorm:"type:int(11);" json:"aid"`          //账户ID
	Bid         int                 `gorm:"type:int(11);" json:"bid"`          //
	Proid       int                 `gorm:"type:int(11);" json:"proid"`        //商品ID
	Name        string              `gorm:"type:varchar(255);" json:"name"`    //规格名称
	Pic         string              `gorm:"type:varchar(255);" json:"pic"`     //规格图片
	MarketPrice decimal.Decimal     `json:"market_price"`                      //市场价
	SellPrice   decimal.Decimal     `json:"sell_price"`                        //销售价
	Sales       int                 `gorm:"type:int(11);" json:"sales"`        //已售数量
	Barcode     string              `gorm:"type:varchar(255);" json:"barcode"` //编码
	Ks          string              `gorm:"type:varchar(255);" json:"ks"`      //规格结构
	Givescore   int                 `gorm:"type:int(11);" json:"givescore"`    //购买给多少积分
	LimitStart  int                 `gorm:"type:int(11);" json:"limit_start"`  //已售数量
	Stock       []models.MFuShopPro `json:"stock"`
}

func GetFuwuProduct(c *gin.Context) {
	//接收
	var jsonData ShopJson
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonData, "")
		return
	}
	//查询
	var list []PostList
	var count int64
	if jsonData.Page == 0 {
		jsonData.Page = -1
	}
	if jsonData.Limit == 0 {
		jsonData.Limit = -1
	}
	offsetVal := (jsonData.Page - 1) * jsonData.Limit
	if jsonData.Page == -1 && jsonData.Limit == -1 {
		offsetVal = -1
	}
	seleData := "m_fu_product.id,m_fu_product.aid,m_fu_product.cate_id,m_fu_product.cate_id2,m_fu_product.cate_id3,m_fu_product.cate_id4," +
		"m_fu_product.cate_id5,m_fu_product.cate_id6,m_shop_category.name as cate_name,a.name as cate_name2,b.name as cate_name3,c.name as cate_name4," +
		"d.name as cate_name5,e.name as cate_name6,m_fu_product.gid,m_fu_product.gid1,m_fu_product.gid2,m_fu_product.gid3,m_fu_product.gid4," +
		"m_fu_product.gid5,m_fu_product.gid6,f.name as gid_name,g.name as gid_name1,h.name as gid_name2,i.name as gid_name3,j.name as gid_name4," +
		"k.name as gid_name5,l.name as gid_name6,m_fu_product.name,m_fu_product.sub_name,m_fu_product.pic,m_fu_product.pics,m_fu_product.sales," +
		"m_fu_product.detail,m_fu_product.market_price,m_fu_product.sell_price,m_fu_product.givescore,m_fu_product.guigedata,m_fu_product.freighttype" +
		",m_fu_product.freightdata,m_fu_product.scoredkmaxset,m_fu_product.scoredkmaxval,m_fu_product.sort,m_fu_product.status,m_fu_product.tj_proid" +
		",m_fu_product.created_at,m_fu_product.type,m_fu_product.tag"
	tx := models.DB.Table("m_fu_product").Select(seleData).Joins("left join m_shop_category on m_shop_category.id=m_fu_product.cate_id").Joins("left join m_shop_category a on a.id=m_fu_product.cate_id2").Joins("left join m_shop_category b on b.id=m_fu_product.cate_id3").Joins("left join m_shop_category c on c.id=m_fu_product.cate_id4").Joins("left join m_shop_category d on d.id=m_fu_product.cate_id5").Joins("left join m_shop_category e on e.id=m_fu_product.cate_id6").Joins("left join m_shop_group f on f.id=m_fu_product.gid").Joins("left join m_shop_group g on g.id=m_fu_product.gid1").Joins("left join m_shop_group h on h.id=m_fu_product.gid2").Joins("left join m_shop_group i on i.id=m_fu_product.gid3").Joins("left join m_shop_group j on j.id=m_fu_product.gid4").Joins("left join m_shop_group k on k.id=m_fu_product.gid5").Joins("left join m_shop_group l on l.id=m_fu_product.gid6").Where("m_fu_product.name LIKE ?", "%"+jsonData.Name+"%")
	if jsonData.Status < 9 {
		tx = tx.Where("m_fu_product.status=?", jsonData.Status)
	}
	if jsonData.Cid > 0 {
		tx = tx.Where("m_fu_product.cate_id=? or m_fu_product.cate_id2=? or m_fu_product.cate_id3=? or m_fu_product.cate_id4=? or m_fu_product.cate_id5=? or m_fu_product.cate_id6=?", jsonData.Cid, jsonData.Cid, jsonData.Cid, jsonData.Cid, jsonData.Cid, jsonData.Cid)
	}
	if jsonData.Gid > 0 {
		tx = tx.Where("m_fu_product.gid=? or m_fu_product.gid1=? or m_fu_product.gi2=? or m_fu_product.gi3=? or m_fu_product.gi4=? or m_fu_product.gid5=? or m_fu_product.gid6=?", jsonData.Gid, jsonData.Gid, jsonData.Gid, jsonData.Gid, jsonData.Gid, jsonData.Gid, jsonData.Gid)
	}
	tx = tx.Count(&count).Limit(jsonData.Limit).Offset(offsetVal).Order("m_fu_product.id desc").Find(&list)
	if tx.Error != nil {
		c.JSON(http.StatusOK, gin.H{
			"success": false,
			"code":    10002,
			"msg":     tx.Error,
		})
	}
	//定义返回的变量
	var listData []FuWuData
	//查询规格
	for _, v := range list {
		//推荐商品
		var listTpro []models.MFuProduct
		if v.TjProid != "" {
			var NewArr = strings.Split(v.TjProid, ",")
			err = models.DB.Model(new(models.MFuProduct)).Where("id IN ?", NewArr).Find(&listTpro).Error
			if err != nil {
				define.Response.ResultFail(c, 10004, err.Error(), "")
				return
			}
		}
		var listfuwu []MShopGuigeFuJson
		//服务规格
		var FuwuGui []models.MShopGuigeFu
		err = models.DB.Model(new(models.MShopGuigeFu)).Where("proid=?", v.ID).Find(&FuwuGui).Error
		if err != nil {
			define.Response.ResultFail(c, 10003, err.Error(), "")
			return
		}
		for _, l := range FuwuGui {
			var FuShopProList []models.MFuShopPro
			err = models.DB.Model(new(models.MFuShopPro)).Where("gid_fid=?", l.ID).Find(&FuShopProList).Error
			if err != nil {
				define.Response.ResultFail(c, 10003, err.Error(), "")
				return
			}
			two := MShopGuigeFuJson{
				ID:          l.ID,
				Name:        l.Name,
				Pic:         l.Pic,
				MarketPrice: l.MarketPrice,
				SellPrice:   l.SellPrice,
				Barcode:     l.Barcode,
				Ks:          l.Ks,
				Givescore:   l.Givescore,
				Stock:       FuShopProList,
			}
			listfuwu = append(listfuwu, two)
		}
		one := FuWuData{
			ShopProduct: v,
			TjProduct:   listTpro,
			FuGuiGe:     listfuwu,
		}
		listData = append(listData, one)

	}
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data": map[string]interface{}{
			"list":  listData,
			"count": count,
		},
	})
}

type FuJsonData struct {
	ID            int                `json:"id"`
	Aid           int                `json:"aid"`                           //账户ID
	Bid           int                `json:"bid"`                           //商户ID
	CateId        int                `gorm:"type:int(10);" json:"cate_id"`  //栏目id
	CateId2       int                `gorm:"type:int(10);" json:"cate_id2"` //栏目id2
	CateId3       int                `gorm:"type:int(10);" json:"cate_id3"` //栏目id3
	CateId4       int                `gorm:"type:int(10);" json:"cate_id4"` //栏目id4
	CateId5       int                `gorm:"type:int(10);" json:"cate_id5"` //栏目id5
	CateId6       int                `gorm:"type:int(10);" json:"cate_id6"` //栏目id6
	Gid           int                `gorm:"type:int(10);" json:"gid"`      //分组ID
	Gid1          int                `gorm:"type:int(10);" json:"gid1"`     //分组ID1
	Gid2          int                `gorm:"type:int(10);" json:"gid2"`     //分组ID2
	Gid3          int                `gorm:"type:int(10);" json:"gid3"`     //分组ID3
	Gid4          int                `gorm:"type:int(10);" json:"gid4"`     //分组ID4
	Gid5          int                `gorm:"type:int(10);" json:"gid5"`     //分组ID5
	Gid6          int                `gorm:"type:int(10);" json:"gid6"`     //分组ID6
	Name          string             `json:"name"`                          //商品名称
	SubName       string             `json:"sub_name"`                      //商品副名称
	Pic           string             `json:"pic"`                           //商品主图
	Pics          string             `json:"pics"`                          //商品图片
	Sales         int                `json:"sales"`                         //已售数量
	Detail        string             `json:"detail"`                        //商品详情
	MarketPrice   float64            `json:"market_price"`                  //市场价
	SellPrice     float64            `json:"sell_price"`                    //销售价
	Givescore     int                `json:"givescore"`                     //购买赠送积分
	Sort          int                `json:"sort"`                          //排序 越大越靠前
	Status        int                `json:"status"`                        //状态0未上架1已上架
	CreatedAt     int                `json:"created_at"`                    //创建时间
	Guigedata     string             `json:"guigedata"`                     //规格数据
	Freighttype   int                `json:"freighttype"`                   //配送方式 1全部模板 0指定模板 3自动发货 4在线卡密
	Freightdata   string             `json:"freightdata"`                   //指定模板时的配送模板ID 多个逗号分割
	Scoredkmaxset int                `json:"scoredkmaxset"`                 //积分抵扣设置 0按照系统设置抵扣 1单独设置抵扣比例 2单独设置抵扣金额 -1不可用积分抵扣
	Scoredkmaxval decimal.Decimal    `json:"scoredkmaxval"`                 //积分抵扣时最多抵扣多少
	GuigeList     []MShopGuigeFuJson `json:"guige_list"`
	TjProid       string             `gorm:"type:varchar(255);" json:"tj_proid"`
	Type          int                `json:"type"`
	Tag           string             `json:"tag"`
}

// 服务商品新增or修改
func AddFuProduc(c *gin.Context) {
	//获取传值
	var jsonData FuJsonData
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  err,
		})
		return
	}
	tx := models.DB.Begin() //开始事务
	if jsonData.ID > 0 {
		//修改数据
		var editData = map[string]interface{}{
			"cate_id":       jsonData.CateId,
			"cate_id2":      jsonData.CateId2,
			"cate_id3":      jsonData.CateId3,
			"cate_id4":      jsonData.CateId4,
			"cate_id5":      jsonData.CateId5,
			"cate_id6":      jsonData.CateId6,
			"gid":           jsonData.Gid,
			"gid1":          jsonData.Gid1,
			"gid2":          jsonData.Gid2,
			"gid3":          jsonData.Gid3,
			"gid4":          jsonData.Gid4,
			"gid5":          jsonData.Gid5,
			"gid6":          jsonData.Gid6,
			"name":          jsonData.Name,
			"sub_name":      jsonData.SubName,
			"pic":           jsonData.Pic,
			"pics":          jsonData.Pics,
			"sales":         jsonData.Sales,
			"detail":        jsonData.Detail,
			"market_price":  decimal.NewFromFloat(jsonData.MarketPrice),
			"sell_price":    decimal.NewFromFloat(jsonData.SellPrice),
			"givescore":     jsonData.Givescore,
			"status":        jsonData.Status,
			"guigedata":     jsonData.Guigedata,
			"freighttype":   jsonData.Freighttype,
			"freightdata":   jsonData.Freightdata,
			"scoredkmaxset": jsonData.Scoredkmaxset,
			"scoredkmaxval": jsonData.Scoredkmaxval,
			"tj_proid":      jsonData.TjProid,
			"type":          jsonData.Type,
			"tag":           jsonData.Tag,
			"updated_at":    int(time.Now().Unix()),
		}
		err = tx.Model(new(models.MFuProduct)).Where("id=?", jsonData.ID).Updates(&editData).Error
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 10003,
				"msg":  err.Error(),
			})
			tx.Rollback()
			return
		}
		//写入日志
		userId, _ := strconv.Atoi(c.GetHeader("userId")) //将字符串转为int
		userName, bid := models.UserName(userId)
		logData := "管理员：" + userName + "，修改了服务商品:" + strconv.Itoa(jsonData.ID) + "的内容"
		models.LogAdd(3, "修改服务商品", userId, logData, bid, jsonData.Aid)
	} else {
		var data models.MFuProduct
		data.Aid = jsonData.Aid
		data.CateId = jsonData.CateId
		data.CateId2 = jsonData.CateId2
		data.CateId3 = jsonData.CateId3
		data.CateId4 = jsonData.CateId4
		data.CateId5 = jsonData.CateId5
		data.CateId6 = jsonData.CateId6
		data.Gid = jsonData.Gid
		data.Gid1 = jsonData.Gid1
		data.Gid2 = jsonData.Gid2
		data.Gid3 = jsonData.Gid3
		data.Gid4 = jsonData.Gid4
		data.Gid5 = jsonData.Gid5
		data.Gid6 = jsonData.Gid6
		data.Name = jsonData.Name
		data.SubName = jsonData.SubName
		data.Pic = jsonData.Pic
		data.Pics = jsonData.Pics
		data.Sales = jsonData.Sales
		data.Detail = jsonData.Detail
		data.MarketPrice = decimal.NewFromFloat(jsonData.MarketPrice)
		data.SellPrice = decimal.NewFromFloat(jsonData.SellPrice)
		data.Givescore = jsonData.Givescore
		data.Status = jsonData.Status
		data.CreatedAt = int(time.Now().Unix())
		data.Guigedata = jsonData.Guigedata
		data.Freighttype = jsonData.Freighttype
		data.Freightdata = jsonData.Freightdata
		data.Sort = 0
		data.TjProid = jsonData.TjProid
		data.Type = jsonData.Type
		data.Tag = jsonData.Tag
		data.Scoredkmaxset = jsonData.Scoredkmaxset
		data.Scoredkmaxval = jsonData.Scoredkmaxval
		err = tx.Model(new(models.MFuProduct)).Create(&data).Error
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 10001,
				"msg":  err.Error(),
			})
			tx.Rollback()
			return
		}
		jsonData.ID = data.ID
		//写入日志
		userId, _ := strconv.Atoi(c.GetHeader("userId")) //将字符串转为int
		userName, bid := models.UserName(userId)
		logData := "管理员：" + userName + "，新增了一个服务商品:" + jsonData.Name
		models.LogAdd(2, "新增服务商品", userId, logData, bid, jsonData.Aid)
	}
	//查询是否存在原有数据
	err = FuGuigeAddDel(jsonData.ID, tx)
	if err != nil {
		define.Response.ResultFail(c, 10001, err.Error(), "")
		tx.Rollback()
		return
	}
	//批量插入数据

	for _, v := range jsonData.GuigeList {
		var one models.MShopGuigeFu
		one.Aid = jsonData.Aid
		one.Proid = jsonData.ID
		one.Name = v.Name
		one.Pic = v.Pic
		one.MarketPrice = v.MarketPrice
		one.SellPrice = v.SellPrice
		one.Ks = v.Ks
		one.Givescore = v.Givescore
		one.Barcode = v.Barcode
		one.Sales = 0
		one.LimitStart = 0
		//批量执行规格数据
		err = tx.Model(new(models.MShopGuigeFu)).Create(&one).Error
		if err != nil {
			define.Response.ResultFail(c, 10002, err.Error(), "")
			tx.Rollback()
			return
		}
		var listData []models.MFuShopPro
		for _, l := range v.Stock {
			two := models.MFuShopPro{
				Aid:         jsonData.Aid,
				Proid:       jsonData.ID,
				GidFid:      one.ID,
				Name:        l.Name,
				MarketPrice: l.MarketPrice,
				SellPrice:   l.SellPrice,
				CostPrice:   l.CostPrice,
				Num:         l.Num,
				CreatedAt:   int(time.Now().Unix()),
			}
			listData = append(listData, two)
		}
		//批量执行规格数据
		err = tx.Model(new(models.MFuShopPro)).Create(&listData).Error
		if err != nil {
			define.Response.ResultFail(c, 10003, err.Error(), "")
			tx.Rollback()
			return
		}
	}
	tx.Commit()
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"msg":     "成功",
	})
}

// 查询是否存在原有规格数据有就删除
func FuGuigeAddDel(id int, tx *gorm.DB) error {
	var roltlist []models.MShopGuigeFu
	var count int64
	err := models.DB.Model(new(models.MShopGuigeFu)).Where("proid=?", id).Count(&count).Find(&roltlist).Error
	if err != nil {
		return err
	}
	//判断是否有数据
	if count > 0 {
		err = tx.Where("proid=?", id).Delete(models.MShopGuigeFu{}).Error
		if err != nil {
			return err
		}
	}
	var Prolist []models.MFuShopPro
	var count2 int64
	err = models.DB.Model(new(models.MFuShopPro)).Where("proid=?", id).Count(&count2).Find(&Prolist).Error
	if err != nil {
		return err
	}
	//判断是否有数据
	if count2 > 0 {
		err = tx.Where("proid=?", id).Delete(models.MFuShopPro{}).Error
		if err != nil {
			return err
		}
	}
	return nil
}

// 删除商品

func FuProducDel(c *gin.Context) {
	var jsonData ProducStatusJson
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  err,
		})
		return
	}
	tx := models.DB.Begin()
	//删除
	err = tx.Delete(&models.MFuProduct{}, jsonData.ID).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10004,
			"msg":  err.Error(),
		})
		tx.Rollback()
		return
	}
	//查询是否存在规格数据
	for i := 0; i < len(jsonData.ID); i++ {
		err = tx.Where("proid=?", jsonData.ID[i]).Delete(models.MShopGuigeFu{}).Error
		if err != nil {
			define.Response.ResultFail(c, 10001, err.Error(), "")
			tx.Rollback()
			return
		}
		err = tx.Where("proid=?", jsonData.ID[i]).Delete(models.MFuShopPro{}).Error
		if err != nil {
			define.Response.ResultFail(c, 10001, err.Error(), "")
			tx.Rollback()
			return
		}
	}
	tx.Commit()
	str := define.ArrayToString(jsonData.ID)
	//写入日志
	userId, _ := strconv.Atoi(c.GetHeader("userId")) //将字符串转为int
	userName, bid := models.UserName(userId)
	logData := "管理员：" + userName + "，删除了服务商品id:" + str
	models.LogAdd(4, "删除服务商品", userId, logData, bid, 1)
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"msg":     "成功！",
	})
}

// 商品服务排序
func FuProducSort(c *gin.Context) {
	//接收id
	var jsonData models.MFuProduct
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  err,
		})
		return
	}
	var data models.MFuProduct
	models.DB.Model(new(models.MFuProduct)).Where("id=?", jsonData.ID).First(&data)
	//修改
	err = models.DB.Model(new(models.MFuProduct)).Where("id=?", jsonData.ID).Update("sort", jsonData.Sort).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10002,
			"msg":  err.Error(),
		})
		return
	}
	//写入日志
	userId, _ := strconv.Atoi(c.GetHeader("userId")) //将字符串转为int
	userName, bid := models.UserName(userId)
	logData := "管理员：" + userName + "，修改服务商品:" + data.Name + "的排序"
	models.LogAdd(5, "服务商品排序", userId, logData, bid, jsonData.Aid)
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"msg":     "成功！",
	})
}

// 服务商品状态修改
func FuProducStatus(c *gin.Context) {
	var jsonData ProducStatusJson
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 1000, define.JsonData, "")
		return
	}
	for i := 0; i < len(jsonData.ID); i++ {
		err = models.DB.Model(new(models.MFuProduct)).Where("id=?", jsonData.ID[i]).Update("status", jsonData.Status).Error
		if err != nil {
			define.Response.ResultFail(c, 10001, err.Error(), "")
			return
		}
	}
	str := define.ArrayToString(jsonData.ID)
	//写入日志
	userId, _ := strconv.Atoi(c.GetHeader("userId")) //将字符串转为int
	userName, bid := models.UserName(userId)
	logData := "管理员：" + userName + "，修改服务商品id:" + str + "的状态"
	models.LogAdd(5, "修改服务商品状态", userId, logData, bid, 1)

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"msg":     "成功！",
	})
}

// 获取服务项目
func FuShopList(c *gin.Context) {
	var jsonData Newdata
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonData, "")
		return
	}
	var list []models.MFuShop
	var count int64
	if jsonData.Page == 0 {
		jsonData.Page = -1
	}
	if jsonData.Limit == 0 {
		jsonData.Limit = -1
	}
	offsetVal := (jsonData.Page - 1) * jsonData.Limit
	if jsonData.Page == -1 && jsonData.Limit == -1 {
		offsetVal = -1
	}
	tx := models.DB.Model(new(models.MFuShop)).Where("aid=? AND name LIKE ?", jsonData.Aid, "%"+jsonData.Name+"%")
	if jsonData.Id > 0 {
		tx = tx.Where("status=?", jsonData.Id)
	}
	tx = tx.Count(&count).Limit(jsonData.Limit).Offset(offsetVal).Order("id desc").Find(&list)
	if err != nil {
		define.Response.ResultFail(c, 10001, err.Error(), "")
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data": map[string]interface{}{
			"list":  list,
			"count": count,
		},
	})
}

// 新增/修改服务项目
func FuShopAdd(c *gin.Context) {
	//获取传值
	var jsonData models.MFuShop
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  err,
		})
		return
	}
	if jsonData.ID > 0 {
		//修改数据
		var editData = map[string]interface{}{
			"name":         jsonData.Name,
			"status":       jsonData.Status,
			"pic":          jsonData.Pic,
			"market_price": jsonData.MarketPrice,
			"sell_price":   jsonData.SellPrice,
			"cost_price":   jsonData.CostPrice,
		}
		err = models.DB.Model(new(models.MFuShop)).Where("id=?", jsonData.ID).Updates(&editData).Error
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 10003,
				"msg":  err.Error(),
			})
			return
		}
		//写入日志
		userId, _ := strconv.Atoi(c.GetHeader("userId")) //将字符串转为int
		userName, bid := models.UserName(userId)
		logData := "管理员：" + userName + "，修改了服务项目:" + strconv.Itoa(jsonData.ID) + "的内容"
		models.LogAdd(3, "修改服务项目", userId, logData, bid, jsonData.Aid)
	} else {
		var data models.MFuShop
		data.Name = jsonData.Name
		data.Pic = jsonData.Pic
		data.Status = jsonData.Status
		data.Aid = jsonData.Aid
		data.MarketPrice = jsonData.MarketPrice
		data.SellPrice = jsonData.SellPrice
		data.CostPrice = jsonData.CostPrice
		data.CreatedAt = int(time.Now().Unix())
		err = models.DB.Model(new(models.MFuShop)).Create(&data).Error
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 10001,
				"msg":  err.Error(),
			})
			return
		}
		//写入日志
		userId, _ := strconv.Atoi(c.GetHeader("userId")) //将字符串转为int
		userName, bid := models.UserName(userId)
		logData := "管理员：" + userName + "，新增了一个服务项目:" + jsonData.Name
		models.LogAdd(2, "新增服务项目", userId, logData, bid, jsonData.Aid)
	}
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"msg":     "成功！",
	})
}

// 删除服务项目
func FuShopDel(c *gin.Context) {
	var jsonData models.MFuShop
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  err,
		})
		return
	}
	var data models.MFuShop
	models.DB.Model(new(models.MFuShop)).Where("id=?", jsonData.ID).First(&data)
	tx := models.DB.Begin()

	//删除
	err = tx.Delete(&models.MFuShop{}, jsonData.ID).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10004,
			"msg":  err.Error(),
		})
		tx.Rollback()
		return
	}
	tx.Commit()

	//写入日志
	userId, _ := strconv.Atoi(c.GetHeader("userId")) //将字符串转为int
	userName, bid := models.UserName(userId)
	logData := "管理员：" + userName + "，删除了一个服务项目:" + data.Name
	models.LogAdd(4, "删除服务项目", userId, logData, bid, jsonData.Aid)
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"msg":     "成功！",
	})
}
